package parse;

import java.util.List;

import model.ParameterModel;
import model.ProductModel;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class Parse {
    public static void getProductData(String html, List<ProductModel> listPro) {
        Document document = Jsoup.parse(html);
        Elements results = document.select("ul[id=JlistItems]")
                .select("li"); //使用CSS选择器定位要解析的所有元素
        //遍历所有元素对应的节点
        for (Element result : results) {
            String product_url = "https:" + result.select("h3").select("a").attr("href");
            String product_id = product_url.replaceAll("\\D", ""); //属性选择器
            String product_name = result.select("h3").select("a").text();
            String product_price = result.select("div[class~=price price-now]").select("a").text();
            //创建对象，将采集到的数据进行封装
            if (product_id.length() != 0) {
                //使用构造方法直接封装数据
                ProductModel model = new ProductModel(product_id, product_name, product_url, product_price);
                listPro.add(model);
            }
        }
    }

    public static void getParData(String url, String html, List<ParameterModel> listPar) {
        Document document = Jsoup.parse(html);
        String product_id = "p" + url.replaceAll("\\D", "");
        Elements results = document.
                select("body[class=index]");
        String parameters = results.select("ul[class=leng-list-param clearfix]").text();
        ParameterModel pModel = new ParameterModel();
        pModel.setProduct_id(product_id);
        pModel.setParameter(parameters);
        listPar.add(pModel);
    }

}